import 'package:flutter/material.dart';

class ShowTextFold extends StatefulWidget {
  final String text;

  final int maxLine;
  ShowTextFold({Key? key, required this.text, this.maxLine = 0})
      : super(key: key);

  @override
  State<ShowTextFold> createState() => _ShowTextFoldState();
}

class _ShowTextFoldState extends State<ShowTextFold> {
  // 全文、收起 的状态
  bool mIsExpansion = false;

  // 最大显示行数
  int mMaxLine = 1;

  late String _text;
  @override
  void initState() {
    _text = widget.text;
    mMaxLine = widget.maxLine;
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    if (isExpansion(_text)) {
      //是否截断
      if (mIsExpansion) {
        return Column(
          children: <Widget>[
            new Text(
              _text,
              textAlign: TextAlign.left,
            ),
            Align(
              alignment: Alignment.centerLeft,
              child: TextButton(
                onPressed: () {
                  _isShowText();
                },
                child: Text("全文"),
              ),
            ),
          ],
        );
      } else {
        return Column(
          children: <Widget>[
            new Text(
              _text,
              maxLines: mMaxLine,
              textAlign: TextAlign.left,
              overflow: TextOverflow.ellipsis,
            ),
            Align(
              alignment: Alignment.centerLeft,
              child: TextButton(
                onPressed: () {
                  _isShowText();
                },
                child: Text("收起"),
              ),
            ),
          ],
        );
      }
    } else {
      return Text(
        _text,
        maxLines: mMaxLine + 1,
        textAlign: TextAlign.left,
        overflow: TextOverflow.ellipsis,
      );
    }
  }

  bool isExpansion(String text) {
    TextPainter _textPainter = TextPainter(
        maxLines: mMaxLine,
        text: TextSpan(
            text: text, style: TextStyle(fontSize: 16.0, color: Colors.black)),
        textDirection: TextDirection.ltr)
      ..layout(maxWidth: 180, minWidth: 50);
    if (_textPainter.didExceedMaxLines) {
      print(_textPainter.height);
      //判断 文本是否需要截断
      return true;
    } else {
      return false;
    }
  }

  void _isShowText() {
    if (mIsExpansion) {
      //关闭
      setState(() {
        mIsExpansion = false;
      });
    } else {
      //打开
      setState(() {
        mIsExpansion = true;
      });
    }
  }
}
